import tkinter as tk
from tkinter import ttk
from trading.core.data_model import MarketData


class StockInfoPanel:
    """股票信息面板：展示实时价格、基本信息和买卖盘口"""

    def __init__(self, parent_frame: ttk.Frame):
        self.frame = ttk.Frame(parent_frame, width=300)
        self._setup_price_frame()
        self._setup_info_frame()
        self._setup_order_frame()

    def _setup_price_frame(self):
        """创建实时价格展示区域"""
        price_frame = ttk.LabelFrame(self.frame, text="实时价格")
        price_frame.pack(fill=tk.X, padx=5, pady=5)

        self.price_var = tk.StringVar(value="--")
        self.change_var = tk.StringVar(value="--")
        self.p_change_var = tk.StringVar(value="--")

        # 价格标签（大号字体）
        price_label = ttk.Label(
            price_frame,
            textvariable=self.price_var,
            font=("SimHei", 24, "bold")
        )
        price_label.pack(pady=10)

        # 涨跌信息
        change_frame = ttk.Frame(price_frame)
        change_frame.pack(pady=5)

        ttk.Label(
            change_frame,
            textvariable=self.change_var,
            font=("SimHei", 14)
        ).pack(side=tk.LEFT, padx=10)

        ttk.Label(
            change_frame,
            textvariable=self.p_change_var,
            font=("SimHei", 14)
        ).pack(side=tk.LEFT, padx=10)

    def _setup_info_frame(self):
        """创建基本信息展示区域"""
        info_frame = ttk.LabelFrame(self.frame, text="基本信息")
        info_frame.pack(fill=tk.X, padx=5, pady=5)

        info_grid = ttk.Frame(info_frame)
        info_grid.pack(fill=tk.X, padx=5, pady=5)

        # 基本信息配置
        info_config = [
            ("今开:", "open_var"),
            ("昨收:", "close_var"),
            ("最高:", "high_var"),
            ("最低:", "low_var"),
            ("成交量:", "volume_var"),
            ("成交额:", "amount_var")
        ]

        self.info_vars = {}
        for i, (label_text, var_name) in enumerate(info_config):
            row = i // 2
            col = (i % 2) * 2

            ttk.Label(info_grid, text=label_text).grid(
                row=row, column=col,
                sticky=tk.W, padx=5, pady=2
            )

            var = tk.StringVar(value="--")
            self.info_vars[var_name] = var
            ttk.Label(info_grid, textvariable=var).grid(
                row=row, column=col + 1,
                sticky=tk.W, padx=5, pady=2
            )

    def _setup_order_frame(self):
        """创建买卖盘口展示区域"""
        order_frame = ttk.LabelFrame(self.frame, text="买卖盘口")
        order_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        self._setup_buy_orders(order_frame)
        self._setup_sell_orders(order_frame)

    def _setup_buy_orders(self, parent_frame: ttk.Frame):
        """创建买盘口区域"""
        header_frame = ttk.Frame(parent_frame)
        header_frame.pack(fill=tk.X, padx=5, pady=2)

        ttk.Label(header_frame, text="买盘", width=8).pack(side=tk.LEFT)
        ttk.Label(header_frame, text="价格", width=10).pack(side=tk.LEFT)
        ttk.Label(header_frame, text="数量", width=10).pack(side=tk.LEFT)

        self.buy_orders = []
        for i in range(5):
            order_frame = ttk.Frame(parent_frame)
            order_frame.pack(fill=tk.X, padx=5)

            ttk.Label(order_frame, text=f"买{i + 1}", width=8).pack(side=tk.LEFT)

            price_var = tk.StringVar(value="--")
            vol_var = tk.StringVar(value="--")

            ttk.Label(
                order_frame,
                textvariable=price_var,
                width=10,
                foreground="red"
            ).pack(side=tk.LEFT)

            ttk.Label(
                order_frame,
                textvariable=vol_var,
                width=10
            ).pack(side=tk.LEFT)

            self.buy_orders.append((price_var, vol_var))

    def _setup_sell_orders(self, parent_frame: ttk.Frame):
        """创建卖盘口区域"""
        header_frame = ttk.Frame(parent_frame)
        header_frame.pack(fill=tk.X, padx=5, pady=2)

        ttk.Label(header_frame, text="卖盘", width=8).pack(side=tk.LEFT)
        ttk.Label(header_frame, text="价格", width=10).pack(side=tk.LEFT)
        ttk.Label(header_frame, text="数量", width=10).pack(side=tk.LEFT)

        self.sell_orders = []
        for i in range(5):
            order_frame = ttk.Frame(parent_frame)
            order_frame.pack(fill=tk.X, padx=5)

            ttk.Label(order_frame, text=f"卖{i + 1}", width=8).pack(side=tk.LEFT)

            price_var = tk.StringVar(value="--")
            vol_var = tk.StringVar(value="--")

            ttk.Label(
                order_frame,
                textvariable=price_var,
                width=10,
                foreground="green"
            ).pack(side=tk.LEFT)

            ttk.Label(
                order_frame,
                textvariable=vol_var,
                width=10
            ).pack(side=tk.LEFT)

            self.sell_orders.append((price_var, vol_var))

    def update_data(self, data: MarketData):
        """更新股票信息面板数据"""
        self._update_price_info(data)
        self._update_basic_info(data)
        self._update_order_info(data)

    def _update_price_info(self, data: MarketData):
        """更新实时价格信息"""
        price = data.price
        change = data.change
        p_change = data.p_change

        if change >= 0:
            self.price_var.set(f"↑  {price:.2f}")
            self.change_var.set(f" 涨 {change:.2f}")
            self.p_change_var.set(f"({p_change:.2f}%)")

            # 设置红色（上涨）
            for widget in self.frame.winfo_children():
                for child in widget.winfo_children():
                    if hasattr(child, 'cget') and child.cget("textvariable") in [
                        str(self.price_var), str(self.change_var), str(self.p_change_var)
                    ]:
                        child.configure(foreground="red")
        else:
            self.price_var.set(f"↓  {price:.2f}")
            self.change_var.set(f" 跌 {abs(change):.2f}")
            self.p_change_var.set(f"({p_change:.2f}%)")

            # 设置绿色（下跌）
            for widget in self.frame.winfo_children():
                for child in widget.winfo_children():
                    if hasattr(child, 'cget') and child.cget("textvariable") in [
                        str(self.price_var), str(self.change_var), str(self.p_change_var)
                    ]:
                        child.configure(foreground="green")

    def _update_basic_info(self, data: MarketData):
        """更新基本信息数据"""
        self.info_vars["open_var"].set(f"{data.open:.2f}")
        self.info_vars["close_var"].set(f"{data.close:.2f}")
        self.info_vars["high_var"].set(f"{data.high:.2f}")
        self.info_vars["low_var"].set(f"{data.low:.2f}")
        self.info_vars["volume_var"].set(f"{data.volume:,}")
        self.info_vars["amount_var"].set(f"{data.amount / 10000:.2f} 万")

    def _update_order_info(self, data: MarketData):
        """更新买卖盘口数据"""
        # 更新买盘
        for i, (price_var, vol_var) in enumerate(self.buy_orders):
            if i < len(data.buy_orders):
                order = data.buy_orders[i]
                price_var.set(f"{order['price']:.2f}")
                vol_var.set(f"{order['volume']:,}")

        # 更新卖盘
        for i, (price_var, vol_var) in enumerate(self.sell_orders):
            if i < len(data.sell_orders):
                order = data.sell_orders[i]
                price_var.set(f"{order['price']:.2f}")
                vol_var.set(f"{order['volume']:,}")